package com.duofan.gmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.auth.feign.MemberFeignService;
import com.duofan.gmall.auth.service.LoginService;
import com.duofan.gmall.auth.vo.UserLoginVo;
import com.duofan.gmall.auth.vo.UserRegVo;
import com.duofan.gmall.common.constant.AuthServerConstant;
import com.duofan.gmall.common.constant.CommonConstant;
import com.duofan.gmall.common.exception.BizCodeEnum;
import com.duofan.gmall.common.utils.R;
import com.duofan.gmall.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    LoginService loginService;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        int res = loginService.sendCode(phone);
        if(res == -1) {
            return R.error(BizCodeEnum.SMS_CODE_EXCEPTION);
        }
        return R.ok();
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null) {
            return "login";
        } else {
            return CommonConstant.REDIRECT_HOME;
        }
    }

    /**
     * 注册接口
     * 重定向携带数据
     * @return
     */
    @PostMapping("/reg")
    public String reg(@Valid UserRegVo vo, BindingResult result, RedirectAttributes attributes) {
        Map<String, String> errors = null;
        if(result.hasErrors()) {
            errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        }

        boolean b = loginService.checkCode(vo);
        // 开发阶段放开验证码
//        if(!b) {
//            errors = new HashMap<>();
//            errors.put("code", "验证码错误");
//        }


        R res = memberFeignService.reg(vo);
        if(res.getCode() != 0) {
            errors = new HashMap<>();
            errors.put("msg", res.getData("msg", new TypeReference<String>(){}));
        }

        if(errors != null) {
            attributes.addFlashAttribute("errors", errors);
            return CommonConstant.REDIRECT_AUTH + "/reg.html";
        }

        // 注册成功回首页,或者回登录页
        return CommonConstant.REDIRECT_AUTH + "/login.html";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0) {
            // 成功
            MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return CommonConstant.REDIRECT_PRE + CommonConstant.URL_HOME;
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors", errors);
            // 远程登录调用失败,重定向到登录页
            return CommonConstant.REDIRECT_AUTH + "/login.html";
        }
    }


    @GetMapping("/logout")
    public String logout(@RequestParam("url") String url, HttpSession session,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        // 清除user session数据
        session.removeAttribute(AuthServerConstant.LOGIN_USER);
        return CommonConstant.REDIRECT_PRE + url;
    }

}
